package com.dzl.admin.service.impl;

import com.dzl.admin.dao.SysRoleMapper;
import com.dzl.admin.pojo.SysAdmin;
import com.dzl.admin.pojo.SysMenu;
import com.dzl.admin.pojo.SysRole;
import com.dzl.admin.pojo.dto.SaveOrUpdateRoleDto;
import com.dzl.admin.pojo.query.SysRoleQuery;
import com.dzl.admin.pojo.vo.RoleComboBoxVo;
import com.dzl.admin.pojo.vo.RoleEditorVo;
import com.dzl.admin.pojo.vo.SysMenuVo;
import com.dzl.admin.pojo.vo.SysRoleVo;
import com.dzl.admin.service.*;
import com.dzl.base.service.BaseServiceImpl;
import com.dzl.config.exception.CommonException;
import com.dzl.constant.CommonConstants;
import com.dzl.util.EmptyUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 角色表(SysRole)表服务实现类
 *
 * @author caobucao
 * @since 2021-05-13 15:49:59
 */
@Service("sysRoleService")
public class SysRoleServiceImpl extends BaseServiceImpl<SysRole> implements SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysRolePermissionService sysRolePermissionService;
    @Autowired
    private SysAdminService sysAdminService;
    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public PageInfo<SysRoleVo> selectRoleListPage(SysRoleQuery query) {
        PageHelper.startPage(query);
        List<SysRoleVo> list = sysRoleMapper.selectRoleListPage(query);
        PageInfo<SysRoleVo> page = new PageInfo<SysRoleVo>(list);
        return page;
    }

    @Override
    public Integer deleteRole(SysRole sysRole) {
        //查看角色是否已有管理员
        Example example = new Example(SysAdmin.class);
        example.createCriteria().andEqualTo("roleId", sysRole.getId()).andEqualTo("status", CommonConstants.YES);
        List<SysAdmin> list = sysAdminService.selectByExample(example);
        if(EmptyUtils.isNotEmpty(list)) {
            throw new CommonException("该角色已有系统用户关联，无法删除！");
        }
        return sysRoleMapper.updateByPrimaryKeySelective(sysRole);
    }

    @Override
    public Integer saveRole(SaveOrUpdateRoleDto param) {
        //查询角色名称是否已存在
        Integer countRole = sysRoleMapper.selectCountRole(param.getId(), param.getName(), param.getEnterpriseId());
        if(countRole > 0) {
            throw new CommonException("角色名重复");
        }
        if(EmptyUtils.isNotEmpty(param.getId())){
            SysRole role=new SysRole();
            role.setId(param.getId());
            role.setName(param.getName());
            role.setUpdater(param.getUpdater());
            role.setUpdateTime(new Date());
            Integer count=sysRoleMapper.updateByPrimaryKeySelective(role);
            if(count>0){
                //根据角色ID删除角色与菜单关联
                sysRoleMenuService.deleteRoleMenuByRoleId(param.getId());
                //根据角色ID删除角色与权限关联关系
                sysRolePermissionService.deleteRolePermissionByRoleId(param.getId());
                //添加角色与菜单关联
                sysRoleMenuService.saveBatchRoleMenu(param.getMenuIds(),param.getId());
                //添加角色与权限关联
                sysRolePermissionService.saveBatchRolePermission(param.getPermissionIds(),role.getId());
            }
            return count;
        }else{
            SysRole role=new SysRole();
            role.setName(param.getName());
            role.setCreateTime(new Date());
            role.setStatus(1);
            role.setCreater(param.getCreater());
            role.setUpdater(param.getUpdater());
            role.setUpdateTime(new Date());
            role.setEnterpriseId(param.getEnterpriseId());
            Integer count=sysRoleMapper.insertSelective(role);
            if(count>0){
                //添加角色与菜单关联
                sysRoleMenuService.saveBatchRoleMenu(param.getMenuIds(),role.getId());
                //添加角色与权限关联
                sysRolePermissionService.saveBatchRolePermission(param.getPermissionIds(),role.getId());
            }
            return count;
        }
    }

    @Override
    public RoleEditorVo queryRoleById(Integer id) {
        RoleEditorVo roleEditorVo=new RoleEditorVo();
        //查询角色详情
        SysRole role=sysRoleMapper.selectByPrimaryKey(id);
        //查询所有菜单
        List<SysMenu> menuList=sysMenuService.queryAllMenu();
        //查询当前角色查询菜单ID集合
         List<Integer>  menuIds=sysRoleMenuService.queryRoleMenuByRoleId(id);
        //根据当前角色查询权限ID集合
        List<Integer> prtmissionIds=sysRolePermissionService.queryRolePermissionByRoleId(id);
        // 0：表示根节点的父ID
        List<SysMenuVo> resultList = editorTransferMenuVo(menuList, 0,menuIds,prtmissionIds);
        roleEditorVo.setId(role.getId());
        roleEditorVo.setName(role.getName());
        roleEditorVo.setMenuVos(resultList);
        return roleEditorVo;
    }

    //封装编辑角色菜单权限树时是否选中节点 allMenu 所有菜单信息, parentId 父节点, menuIds 当前角色的所有菜单Id ,prtmissionIds当前角色的所有权限
    private List<SysMenuVo> editorTransferMenuVo(List<SysMenu> allMenu, Integer parentId, List<Integer> menuIds,List<Integer> prtmissionIds){
        List<SysMenuVo> resultList=new ArrayList<>();
        if(!CollectionUtils.isEmpty(allMenu)){
            for(SysMenu source:allMenu){
                if(parentId.equals(source.getParentId())){
                    SysMenuVo menuVo=new SysMenuVo(source);
                    if(source.getParentId()==0) {
                        menuVo.setRedirect("noredirect");
                    }
                    //递归查询子菜单，并封装信息
                    List<SysMenuVo> childList=editorTransferMenuVo(allMenu,source.getId(),menuIds,prtmissionIds);
                    if(!CollectionUtils.isEmpty(childList)){
                        menuVo.setChildren(childList);
                        //循环子菜单 查询子菜单下按钮
                        childList.forEach(menuNav->{

                        });
                    }
                    if(menuIds.contains(menuVo.getId())){
                        menuVo.setSelect(true);
                    }
                    resultList.add(menuVo);
                }
            }
        }
        return resultList;
    }

    @Override
    public List<SysMenuVo> queryByRoleIdMenuTree(Integer roleId, Integer isEnable) {
        List<SysMenu> menuList=sysRoleMenuService.queryByRoleIdMenu(roleId,isEnable);
        // 0：表示根节点的父ID
        List<SysMenuVo> resultList = transferMenuVo(menuList, 0);
        return resultList;
    }

    @Override
    public List<RoleComboBoxVo> queryRoleComboBox(Integer enterpriseId) {
        return sysRoleMapper.queryRoleAll(enterpriseId);
    }

    private List<SysMenuVo> transferMenuVo(List<SysMenu> allMenu, Integer parentId){
        List<SysMenuVo> resultList=new ArrayList<>();
        if(!CollectionUtils.isEmpty(allMenu)){
            for(SysMenu source:allMenu){
                if(parentId.equals(source.getParentId())){
                    SysMenuVo menuVo=new SysMenuVo(source);
                    if(source.getParentId()==0) {
                        menuVo.setRedirect("noredirect");
                    }
                    //递归查询子菜单，并封装信息
                    List<SysMenuVo> childList=transferMenuVo(allMenu,source.getId());
                    if(!CollectionUtils.isEmpty(childList)){
                        menuVo.setChildren(childList);
                    }
                    resultList.add(menuVo);
                }
            }
        }
        return resultList;
    }
}
